<template>
    <div>
        <van-nav-bar
                title="地址管理"
                left-arrow
                class="my-nav"
                :fixed="true"
                @click-left="$router.back(-1)"
        />
        <div style="margin-top: 50px;">
            <van-address-list
                    v-model="chosenAddressId"
                    :list="list"
                    @edit="onEdit"
                    @select="onSelect"
            >
                <van-button bottomAction  class="van-address-list__add"  style="z-index: 10000;background: #fff "></van-button>
                <van-button v-if="isAdd"  bottomAction type="primary" class="van-address-list__add"  style="z-index: 10001; " @click="onAdd">新增地址</van-button>
                <van-button v-else disabled bottomAction type="primary" class="van-address-list__add"  style="z-index: 10001;" >最多添加三个收货地址</van-button>
            </van-address-list>
        </div>

    </div>
</template>

<script>
    import {Toast} from 'vant'
    import {listAddress,updataDefauleAddress} from '../../api/address'

    export default {
        data() {
            return {
                chosenAddressId: '',
                list: [
                    /* {
                       id: '1',
                       name: '张三',
                       tel: '13000000000',
                       address: '浙江省杭州市西湖区文三路 138 号东方通信大厦 7 楼 501 室'
                     },
                     {
                       id: '2',
                       name: '李四',
                       tel: '1310000000',
                       address: '浙江省杭州市拱墅区莫干山路 50 号'
                     }*/
                ],
            }
        },
        mounted() {
            listAddress(d => {
                for (let i of d.data) {
                    let obj = {}
                    obj.id = i.id
                    obj.name = i.name
                    obj.tel = i.phone
                    obj.address = i.region + i.address
                    if (true == i.enabled) {
                        this.chosenAddressId = i.id
                    }
                    this.list.push(obj)
                }
            })

        },
        methods: {
            onAdd() {
                this.$router.push('address-edit')
            },

            onEdit(item, index) {
                this.$router.push({path:'address-edit',query:{id:item.id}});
            },
            onSelect(item){
                updataDefauleAddress(item.id, _ => Toast('设置默认收货地址成功!'), _ => Toast('设置默认收货地址失败!'))
            }
        },
        computed: {
            isAdd(){
                return this.list.length<3;
            }
        }
    }
</script>

<style lang="less" scoped>

</style>